package com.coollang.smartbra.views;

import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.constant.ResourceList;
import com.coollang.smartbra.fragment.FirstFragment;
import com.coollang.smartbra.interfaces.ActionType;
import com.coollang.smartbra.model.ActionDataModel;
import com.coollang.smartbra.model.TodayPlanDetail;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.utils.Utils;
import com.white.progressview.CircleProgressView;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * @author: Timmy
 * @data: 2017/12/25
 * @Fuction:
 */
public class MainCircleHelper {
    public static final String TAG = "MainCircleHelper";
    private FirstFragment mFirstFragment;

    private static final int ACTION_LENGTH = ResourceList.actionImage.length;

    /**
     * 最外层LinearOut
     */
    private LinearLayout mLinearLayout1;
    private LinearLayout mLinearLayout2;
    private LinearLayout mLinearLayout3;
    private LinearLayout mLinearLayout4;
    private LinearLayout mLinearLayout5;
    private LinearLayout mLinearLayout6;
    private LinearLayout mLinearLayout7;


    /**
     * =========== 圆圈图片 ===========
     */
    private ImageView mImageView1;
    private ImageView mImageView2;
    private ImageView mImageView3;
    private ImageView mImageView4;
    private ImageView mImageView5;
    private ImageView mImageView6;
    private ImageView mImageView7;

    private TextView mTextView1;
    private TextView mTextView2;
    private TextView mTextView3;
    private TextView mTextView4;
    private TextView mTextView5;
    private TextView mTextView6;
    private TextView mTextView7;

    private TextView mTvActionTitle;
    private TextView mTvActionState;

    private int mCurrentItem = 3;
    private ImageView mIvFistGo;
    private CircleProgressView mCircleProgressView;
    private CircleProgressView mCircleProgressView0;
    private CircleProgressView mCircleProgressView1;
    private CircleProgressView mCircleProgressView2;
    private CircleProgressView mCircleProgressView3;
    private CircleProgressView mCircleProgressView4;

    public MainCircleHelper(FirstFragment firstFragment) {
        mFirstFragment = firstFragment;
        initView(mFirstFragment.getView());
        initData();
    }

    private void initView(View view) {

        mLinearLayout1 = (LinearLayout) view.findViewById(R.id.ll_sd);
        mLinearLayout2 = (LinearLayout) view.findViewById(R.id.ll_sdt);
        mLinearLayout3 = (LinearLayout) view.findViewById(R.id.ll_ywqz);
        // 最中间大的
        mLinearLayout4 = (LinearLayout) view.findViewById(R.id.ll_bx);
        mLinearLayout5 = (LinearLayout) view.findViewById(R.id.ll_jf);
        mLinearLayout6 = (LinearLayout) view.findViewById(R.id.ll_fwc);
        mLinearLayout7 = (LinearLayout) view.findViewById(R.id.ll_pbzc);

        mImageView1 = (ImageView) view.findViewById(R.id.iv_fist_sd);
        mImageView1.setBackgroundResource(ResourceList.actionImage[getIndex(-3)]);
        mImageView2 = (ImageView) view.findViewById(R.id.iv_fist_sdt);
        mImageView2.setBackgroundResource(ResourceList.actionImage[getIndex(-2)]);
        mImageView3 = (ImageView) view.findViewById(R.id.iv_fist_ywqz);
        mImageView3.setBackgroundResource(ResourceList.actionImage[getIndex(-1)]);
        // 最中间大的
        mImageView4 = (ImageView) view.findViewById(R.id.iv_fist_bx);
        mImageView4.setBackgroundResource(ResourceList.actionImage_pressed[getIndex(0)]);
        mImageView5 = (ImageView) view.findViewById(R.id.iv_fist_jf);
        mImageView5.setBackgroundResource(ResourceList.actionImage[getIndex(+1)]);
        mImageView6 = (ImageView) view.findViewById(R.id.iv_fist_fwc);
        mImageView6.setBackgroundResource(ResourceList.actionImage[getIndex(+2)]);
        mImageView7 = (ImageView) view.findViewById(R.id.iv_fist_pbzc);
        mImageView7.setBackgroundResource(ResourceList.actionImage[getIndex(+3)]);

        // TextView
        mTextView1 = (TextView) view.findViewById(R.id.tv_sd_go);
        mTextView1.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[0]);
        mTextView2 = (TextView) view.findViewById(R.id.tv_sdt_go);
        mTextView2.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[1]);
        mTextView3 = (TextView) view.findViewById(R.id.tv_ywqz_go);
        mTextView3.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[2]);
        // 最中间大的
        mTextView4 = (TextView) view.findViewById(R.id.tv_bx_go);
        mTextView4.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[3]);
        mTextView5 = (TextView) view.findViewById(R.id.tv_jf_go);
        mTextView5.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[4]);
        mTextView6 = (TextView) view.findViewById(R.id.tv_fwc_go);
        mTextView6.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[5]);
        mTextView7 = (TextView) view.findViewById(R.id.tv_pbzc_go);
        mTextView7.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[6]);

        mLinearLayout1.setOnClickListener(mOnClickListener);
        mLinearLayout2.setOnClickListener(mOnClickListener);
        mLinearLayout3.setOnClickListener(mOnClickListener);
        mLinearLayout4.setOnClickListener(mOnClickListener);
        mLinearLayout5.setOnClickListener(mOnClickListener);
        mLinearLayout6.setOnClickListener(mOnClickListener);
        mLinearLayout7.setOnClickListener(mOnClickListener);

        mIvFistGo = (ImageView) view.findViewById(R.id.iv_fist_go);
        mIvFistGo.setOnClickListener(mOnClickListener);

        mTvActionTitle = (TextView) view.findViewById(R.id.action_title);
        mTvActionState = (TextView) view.findViewById(R.id.action_state);

        // 进度条

        mCircleProgressView = view.findViewById(R.id.circle_progress_normal);
        mCircleProgressView0 = view.findViewById(R.id.circle_progress_normal0);
        mCircleProgressView1 = view.findViewById(R.id.circle_progress_normal1);
        mCircleProgressView2 = view.findViewById(R.id.circle_progress_normal2);
        mCircleProgressView3 = view.findViewById(R.id.circle_progress_normal3);
        mCircleProgressView4 = view.findViewById(R.id.circle_progress_normal4);


        int reachBarColor = ContextCompat.getColor(mFirstFragment.getActivity(), R.color.main_progress);
        int normalBarColor = adjustAlpha(reachBarColor, 0.3f);

        mCircleProgressView.setReachBarColor(reachBarColor);
        mCircleProgressView.setNormalBarColor(normalBarColor);

        mCircleProgressView0.setReachBarColor(reachBarColor);
        mCircleProgressView0.setNormalBarColor(normalBarColor);

        mCircleProgressView1.setReachBarColor(reachBarColor);
        mCircleProgressView1.setNormalBarColor(normalBarColor);

        mCircleProgressView2.setReachBarColor(reachBarColor);
        mCircleProgressView2.setNormalBarColor(normalBarColor);

        mCircleProgressView3.setReachBarColor(reachBarColor);
        mCircleProgressView3.setNormalBarColor(normalBarColor);

        mCircleProgressView4.setReachBarColor(reachBarColor);
        mCircleProgressView4.setNormalBarColor(normalBarColor);

        initProgress();
    }

    private void initProgress() {
        mCircleProgressView.setProgress(0);
        mCircleProgressView0.setProgress(0);
        mCircleProgressView1.setProgress(0);
        mCircleProgressView2.setProgress(0);
        mCircleProgressView3.setProgress(0);
        mCircleProgressView4.setProgress(0);
    }

    /**
     * 显示步数
     */
    private void initData() {
        ActionDataModel dataModel = Realm.getDefaultInstance().where(ActionDataModel.class)
                .equalTo(Constants.TYPE, ActionType.WALK)
                // 大于今日凌晨的时间
                .greaterThan(Constants.ID, TimeUtils.getToDayZero())
                .findFirst();

        if (dataModel != null) {
            mTvActionTitle.setVisibility(View.VISIBLE);
            setStepNumber(dataModel.getNums() + " 步");
        } else {
            mTvActionTitle.setVisibility(View.GONE);
            mTvActionState.setText("暂无运动记录");
        }
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.ll_sd:
                    onClickItem(-3);
                    break;
                case R.id.ll_sdt:
                    onClickItem(-2);
                    break;
                case R.id.ll_ywqz:
                    onClickItem(-1);
                    break;
                case R.id.ll_bx:
                    onClickItem(0);
                    break;
                case R.id.ll_jf:
                    onClickItem(1);
                    break;
                case R.id.ll_fwc:
                    onClickItem(2);
                    break;
                case R.id.ll_pbzc:
                    onClickItem(3);
                    break;
                case R.id.iv_fist_go:
                    // 点击了go按钮
                    if (MyApplication.getApplication().isConnected) {
                        gotoAction();
                    } else {
                        ToastUtils.showToast(UIUtils.getString(R.string.ble_disconnect));
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void onClickItem(int item) {

        int index = mCurrentItem;
        // 当前选中的运动
        mCurrentItem = getIndex(item);
        if (index == mCurrentItem) {
            return;
        } else {
            // 查询运动数据
            int actionType = Constants.ACTION_NAME_ID2[mCurrentItem];
            loadSQLData(actionType);
            loadProgressSQLData();
        }

        setResource();

        /**
         * 显示隐藏go按钮
         */
        if (mCurrentItem == 3) {
            BleUtil.getInstance().sendData((byte) 0x30);
            mIvFistGo.setVisibility(View.INVISIBLE);
            mFirstFragment.setTongbuText("同步一下");
        } else {
            mIvFistGo.setVisibility(View.VISIBLE);
            mFirstFragment.setTongbuText("查看计划");
        }
    }

    private void setResource() {
        // 修改图片
        mImageView1.setBackgroundResource(ResourceList.actionImage[getIndex(-3)]);
        mImageView2.setBackgroundResource(ResourceList.actionImage[getIndex(-2)]);
        mImageView3.setBackgroundResource(ResourceList.actionImage[getIndex(-1)]);
        mImageView4.setBackgroundResource(ResourceList.actionImage_pressed[mCurrentItem]);
        mImageView5.setBackgroundResource(ResourceList.actionImage[getIndex(1)]);
        mImageView6.setBackgroundResource(ResourceList.actionImage[getIndex(2)]);
        mImageView7.setBackgroundResource(ResourceList.actionImage[getIndex(3)]);

        // 修改文字
        mTextView1.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[getIndex(-3)]);
        mTextView2.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[getIndex(-2)]);
        mTextView3.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[getIndex(-1)]);
        mTextView4.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[mCurrentItem]);
        mTextView5.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[getIndex(1)]);
        mTextView6.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[getIndex(2)]);
        mTextView7.setText(ResourceList.CIRCLE_ACTION_NAME_LIST[getIndex(3)]);
    }

    private void loadSQLData(int actionType) {
        // 查询数据库
        // 或者进行简化
        Realm realm = Realm.getDefaultInstance();
        RealmResults<ActionDataModel> result2 = realm.where(ActionDataModel.class)
                .equalTo(Constants.TYPE, actionType)
                // 大于今日凌晨的时间
                .greaterThan(Constants.ID, TimeUtils.getToDayZero())
                .findAll();

        List<ActionDataModel> dataModels = realm.copyFromRealm(result2);
        // 过滤, 获取今日时间的
        filterTime(actionType, dataModels);
    }

    private void filterTime(int actionType, List<ActionDataModel> dataModels) {
        if (dataModels.size() > 0) {
            int actionCount = 0;
            for (ActionDataModel dataModel : dataModels) {
                actionCount += dataModel.getNums();
            }

            switch (actionType) {
                case ActionType.PBZC:
                    // 平板支撑
                    if (actionCount == 0) {
                        mTvActionTitle.setVisibility(View.GONE);
                        mTvActionState.setText("暂无运动记录");
                    } else {
                        mTvActionTitle.setText("今日坚持");
                        mTvActionTitle.setVisibility(View.VISIBLE);
                        String[] split = TimeUtils.secToTime(actionCount).split("\"");
                        setPbzcNumber(split[split.length - 2] + " 分 " + split[split.length - 1] + " 秒");
                    }

                    break;
                case ActionType.WALK:
                    if (actionCount == 0) {
                        mTvActionTitle.setVisibility(View.GONE);
                        mTvActionState.setText("暂无运动记录");
                    } else {
                        mTvActionTitle.setText("今日步数");
                        mTvActionTitle.setVisibility(View.VISIBLE);
                        setStepNumber(actionCount + " 步");
                    }
                    break;
                default:
                    if (actionCount == 0) {
                        mTvActionTitle.setVisibility(View.GONE);
                        mTvActionState.setText("暂无运动记录");
                    } else {
                        mTvActionTitle.setText("今日坚持");
                        mTvActionTitle.setVisibility(View.VISIBLE);
                        setStepNumber(actionCount + " 个");
                    }
                    break;
            }

        } else {
            mTvActionTitle.setVisibility(View.GONE);
            mTvActionState.setText("暂无运动记录");
        }
    }

    private int getIndex(int item) {
        return (mCurrentItem + item + ACTION_LENGTH) % ACTION_LENGTH;
    }

    private void gotoAction() {
        if (mCurrentItem < 3) {
            ActivitySwitcher.goToNewAction(mFirstFragment.getActivity(), mCurrentItem);
        } else if (mCurrentItem > 3) {
            int index = mCurrentItem - 1;
            ActivitySwitcher.goToNewAction(mFirstFragment.getActivity(), index);
        }
    }

    private void setStepNumber(String text) {
        // 设置字体大小
        SpannableString msp = new SpannableString(text);
        msp.setSpan(new RelativeSizeSpan(2.0f), 0, text.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvActionState.setText(msp);
    }

    private void setPbzcNumber(String text) {
        SpannableString msp = new SpannableString(text);
        msp.setSpan(new RelativeSizeSpan(2.0f), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new RelativeSizeSpan(2.0f), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvActionState.setText(msp);
    }

    /**
     * 获取颜色的透明度
     */
    private int adjustAlpha(int color, float factor) {
        int alpha = Math.round(Color.alpha(color) * factor);
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        return Color.argb(alpha, red, green, blue);
    }

    public void loadProgressSQLData() {
        initProgress();

        Realm realm = Realm.getDefaultInstance();
        RealmResults<TodayPlanDetail> result = realm.where(TodayPlanDetail.class)
                .findAll();


        // 查询运动数据
        int action1 = Constants.ACTION_NAME_ID2[getIndex(-3)];
        int action2 = Constants.ACTION_NAME_ID2[getIndex(-2)];
        int action3 = Constants.ACTION_NAME_ID2[getIndex(-1)];

        int action4 = Constants.ACTION_NAME_ID2[getIndex(1)];
        int action5 = Constants.ACTION_NAME_ID2[getIndex(2)];
        int action6 = Constants.ACTION_NAME_ID2[getIndex(3)];


        for (TodayPlanDetail planDetail : result) {
            int actionID = planDetail.getActionID();
            int actionCount = planDetail.getActionCount();
            long finishCount = planDetail.getFinishCount();

            if (finishCount != 0) {
                int numberPercent;
                if (finishCount > actionCount) {
                    numberPercent = 100;
                } else {
                    numberPercent = Integer.parseInt(Utils.getNumberPercent((int) finishCount, actionCount));
                }

                if (actionID == action1) {
                    mCircleProgressView.setProgress(numberPercent);
                } else if (actionID == action2) {
                    mCircleProgressView0.setProgress(numberPercent);
                } else if (actionID == action3) {
                    mCircleProgressView1.setProgress(numberPercent);
                } else if (actionID == action4) {
                    mCircleProgressView2.setProgress(numberPercent);
                } else if (actionID == action5) {
                    mCircleProgressView3.setProgress(numberPercent);
                } else if (actionID == action6) {
                    mCircleProgressView4.setProgress(numberPercent);
                }
            }
        }
    }

    public int getCurrentItem() {
        return mCurrentItem;
    }
}
